const express = require("express")
const router = express.Router()
const Article = require("../controllers/articleController")
const articleObj = new Article()
const Jwt = require("../common/jwt")
const OperationLog = require("../controllers/operationLogController")
const operationLogObj = new OperationLog()
const db = require("../common/db/index")

router.post("/publish", async (req, res) => {
    let { title, cate, cate_name, content, src, tag, status } = req.body;
    let token = req.headers.token || req.body.token;

    if (token == undefined || title == undefined || cate == undefined || cate_name == undefined || content == undefined || src == undefined || tag == undefined) {
        res.send({
            code: -1,
            msg: "缺少参数",
            params: { title, cate, cate_name, content, src, tag }
        })
    }
    else {
        let result = new Jwt(token).verifyToken();
        if (result.code == 200) {
            const adminId = result.info.data
            await articleObj.publish(title, adminId, cate, cate_name, content, src, tag, status)
                .then(
                    async (publishResult) => {
                        try {
                            const adminResult = await db.query('SELECT username FROM pre_user WHERE id = ?', [adminId])
                            const adminName = adminResult[0]?.username || '管理员'
                            await operationLogObj.add(adminId, adminName, '发布文章', `发布文章：${title}`)
                        } catch (logErr) {
                            console.error('记录操作日志失败:', logErr)
                        }
                        res.status(200).json(publishResult);
                    },
                    err => {
                        res.status(500).json(err)
                    }
                )
        }
        else {
            res.status(400).json({ msg: "您尚未登录" })
        }
    }

})

router.post("/items", async (req, res) => {
    let { page_num, page_size } = req.body
    if (page_num == undefined || page_size == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        await articleObj.items(page_num, page_size)
            .then(
                result => {
                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json(err)
                }
            )
    }
})

router.post("/delete", async (req, res) => {
    let id = req.body.id
    let token = req.headers.token;
    if (id == undefined || token == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        let result = new Jwt(token).verifyToken();
        if (result.code == 200) {
            const adminId = result.info.data
            let articleInfo = null
            try {
                const articleResult = await articleObj.detail(id)
                if (articleResult && articleResult.length > 0) {
                    articleInfo = articleResult[0]
                }
            } catch (err) {
                console.error('获取文章信息失败:', err)
            }

            await articleObj.remove(id)
                .then(
                    async (result) => {
                        try {
                            const adminResult = await db.query('SELECT username FROM pre_user WHERE id = ?', [adminId])
                            const adminName = adminResult[0]?.username || '管理员'
                            const articleTitle = articleInfo?.title || '未知文章'
                            await operationLogObj.add(adminId, adminName, '删除文章', `删除文章：${articleTitle}`)
                        } catch (logErr) {
                            console.error('记录操作日志失败:', logErr)
                        }
                        res.status(200).json(result);
                    },
                    err => {
                        res.status(500).json(err)
                    }
                )
        }
        else {
            res.status(400).json({ msg: "您尚未登录" })
        }
    }
})

router.post("/search", async (req, res) => {
    let { keyword } = req.body
    if (keyword == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        await articleObj.search(keyword)
            .then(
                result => {
                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json(err)
                }
            )
    }
})

router.post("/detail", async (req, res) => {
    let { id } = req.body
    if (id == undefined) {
        res.status(404).json({ code: -1, msg: "缺少参数" })
    }
    else {
        await articleObj.detail(id)
            .then(
                result => {
                    res.status(200).json({
                        code: 200,
                        msg: "获取文章详情成功",
                        result: result
                    });
                },
                err => {
                    res.status(500).json({
                        code: 500,
                        msg: "获取文章详情失败",
                        err: err
                    })
                }
            )
    }
})

router.post("/modify", async (req, res) => {
    let { title, cate, cate_name, content, src, tag, id, status, is_top } = req.body
    if (title == undefined || cate == undefined || cate_name == undefined || content == undefined || src == "" || tag == undefined || id == undefined) {
        res.status(404).json({ code: -1, msg: "缺少参数" })
    }
    else {
        let token = req.headers.token // || req.body.token;
        if (token == undefined) {
            res.status(404).json({ code: -1, msg: "缺少参数" })
        }
        else {
            let result = new Jwt(token).verifyToken();
            if (result.code == 200) {
                const adminId = result.info.data
                await articleObj.modify(title, adminId, cate, cate_name, content, src, tag, id, status, is_top)
                    .then(
                        async (result) => {
                            try {
                                const adminResult = await db.query('SELECT username FROM pre_user WHERE id = ?', [adminId])
                                const adminName = adminResult[0]?.username || '管理员'
                                await operationLogObj.add(adminId, adminName, '修改文章', `修改文章：${title}`)
                            } catch (logErr) {
                                console.error('记录操作日志失败:', logErr)
                            }
                            res.status(200).json(result);
                        },
                        err => {
                            res.status(500).json(err)
                        }
                    )
            }
            else {
                res.status(400).json({ code: -1, msg: "您尚未登录" })
            }
        }
    }
})

router.get("/hot", async (req, res) => {
    let limit = parseInt(req.query.limit) || 10;
    await articleObj.getHotArticles(limit)
        .then(
            result => {
                res.status(200).json(result);
            },
            err => {
                res.status(500).json(err)
            }
        )
})

router.post("/list", async (req, res) => {
    let { page_num, page_size, cate_name } = req.body;
    if (page_num == undefined || page_size == undefined) {
        res.status(404).json({ code: -1, msg: "缺少参数" })
    } else {
        await articleObj.list(page_num, page_size, cate_name)
            .then(
                result => {
                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json(err)
                }
            )
    }
})

module.exports = router;